<?php
/**
 * Created by PhpStorm.
 * User: Jason.Jiang
 * Date: 2015/9/18
 * Time: 11:42
 */

class Model
{

    public $model_name = '';
    public $model_upper = '';
    public $model_folder = '';

    private $model_template = '';
    private $prefix = '';
    private $column;

    public function __construct($model, $prefix, $columns)
    {
        $this->model_name = strtolower($model);
        $this->model_upper = ucfirst($this->model_name);
        $this->model_folder = PROJECT_PATH . DS . 'application' . DS . 'models';
        $this->model_template = MODULE . DS . 'model' . DS . 'model.template.html';
        $this->prefix = $prefix;
        $this->column = $columns;
        $this->run();
    }

    public function run()
    {
        $data_str = $this->mkColumn();
        $model_template = @file_get_contents($this->model_template);
        $model_con = str_replace(array('{$controller_name}', '{$pre_fix}', '{$controller_lower}', '{$data_str}'), array($this->model_upper,$this->prefix, $this->model_name, $data_str), $model_template);
        $model_path =  $this->model_folder . DS .$this->model_name . '.php';
        @file_put_contents($model_path, $model_con);
    }

    public function mkColumn()
    {
        if(!$this->column)
        {
            return false;
        }

        if(!is_array($this->column) || !is_array($this->column))
        {
            return false;
        }

        $result_str = '';
        foreach($this->column as $val)
        {
            if($val != 'id')
            {
                if($val == 'ctime')
                {
                    $result_str .= "\$save_data['{$val}'] = time();" . PHP_EOL . "        ";
                } else {
                    $result_str .= "\$save_data['{$val}'] = \$data['{$val}'];" . PHP_EOL . "        ";
                }
            }
        }

        return $result_str;
    }
}